<template>
  <div>
    <el-card style="max-width: 240px" shadow="hover">
      <template #header>
        <i-ep-List />
        随机文章
      </template>
      <div class="body" v-for="item in randomdata" :key="item._id" @click="todetail(item._id)">
        <img :src="item.image || `https://free-img.400040.xyz/4/2024/06/24/66794c3bcb54b.jpg`" class="img" />
        <div class="info">
          <p><i-ep-Calendar /> {{$moment(item.time).format('YYYY年MM月DD日 HH时')}}</p>
          <p><i-ep-Flag /> <span style="position: relative;top: -5px;">{{item.title}}</span></p>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { onMounted, ref, watch } from "vue";
import { useRouter } from "vue-router";
const props = defineProps({
  data:{
    type: Array,
    default: []
  }
})
const router = useRouter()
let randomdata = ref([])
const randomfn = ()=>{
  //随机数加去重
  const selectedIndices = new Set();
  const result = []
  while (result.length < 3 && props.data.length > 0 ) {
    let resultindex 
    do {
      resultindex = Math.floor(Math.random()*props.data.length)
    } while (selectedIndices.has(resultindex))
    selectedIndices.add(resultindex)
    result.push(props.data[resultindex])
    if (selectedIndices.size === props.data.length) break; 
    console.log(resultindex, '随机数');
  }
  console.log(result, '随机文章');
  // randomdata.value = result
  randomdata.value = result
} 
const todetail = (id) =>{
  console.log('点击了右侧随机文章');
  router.push({path:'/blog', query:{id}})
}
watch(() => props.data, (newData, oldData) => {  
  console.log(newData, '右侧随机文章');  
  if (newData.length > 3 && newData !== oldData) {  
    randomfn();  
  }  else if(newData.length > 0 && newData !== oldData) {
    console.log('object', newData);
    randomdata.value = newData;  
  }
});  

</script>

<style lang="less" scoped>
.body {
  height: 200px;
  padding: 10px 0;
  cursor: pointer;
}
.info {
  text-align: left;
  margin: 0 auto;
  position: relative;
  bottom: 70px;
  padding-left: 10px;
  font-size: 14px;
  color: #fff;
}
.img {
  width: 100%;
  object-fit: cover;
  border-radius: 10px;
}
</style>
